package com.sun.service.impl;

import com.sun.dao.UserMapper;
import com.sun.entity.User;
import com.sun.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {


	private UserMapper userMapper;
	@Override
	public User selectUserById(Integer id) {
		try {
			return userMapper.selectUserById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public int addUser(User user) {
		try {
			return userMapper.addUser(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public List<User> getUserList() throws Exception {
		return userMapper.getUserList();
	}

	@Override
	public User updateByid(Integer id, User updatedUser) throws Exception {
		// 从数据库中获取当前用户信息
		User existingUser = userMapper.selectUserById(id);
		if (existingUser == null) {
			throw new RuntimeException("User not found with id: " + id);
		}

		// 更新用户信息
		existingUser.setName(updatedUser.getName());

		existingUser.setAge(updatedUser.getAge());


		// 保存到数据库
		userMapper.updateByid(existingUser);

		// 返回更新后的用户信息
		return  existingUser;

	}

	@Override
	public void deleteByid(Integer id) {
		userMapper.deleteByid(id);
	}

	/*使用通用Mapper*/
	@Override
	@Transactional
	public int updateUser(User user) {
		return  userMapper.updateByPrimaryKeySelective(user);
	}
}